package com.yanqu.road.server.timer.newmonopolymarker;

import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.systemgroup.newmonopolymarket.NewMonopolyMarketNoticeData;
import com.yanqu.road.entity.systemgroup.newmonopolymarket.resgrab.NewMonopolyMarketResGrabPointInfo;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.pb.newmonopolymkt.NewMonopolyMarketProto;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.systemgroup.newmonopolymkt.CrossNewMonopolyMarketGroup;
import com.yanqu.road.server.manager.systemgroup.newmonopolymkt.CrossNewMonopolyMarketMgr;
import com.yanqu.road.server.manager.systemgroup.newmonopolymkt.NewMonopolyMarketResGrab;
import com.yanqu.road.server.manager.user.CrossUserMgr;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.executor.GeneralTask;

import java.util.*;

public class CrossNewMonopolyMarketTask extends GeneralTask {

    @Override
    public void doRun() {

        try{
            //上传区服能力
            int weekId = GameConfig.getSystemThisWeekId();
            for (Map.Entry<Integer, Map<Integer, CrossNewMonopolyMarketGroup>> entry : CrossNewMonopolyMarketMgr.getMarketMap().entrySet()) {
                if(entry.getKey() != weekId){
                    continue;
                }
                for (Map.Entry<Integer, CrossNewMonopolyMarketGroup> groupEntry : entry.getValue().entrySet()) {
                    groupEntry.getValue().checkActiveUserUploadAbility();
                }
            }
        }catch (Exception e){
            CrossNewMonopolyMarketMgr.getLogger().info("error:", e);
        }

        try{
            //榷署的座位根据活跃玩家的数量来确定，需要定时初始化
            int weekId = GameConfig.getSystemThisWeekId();
            for (Map.Entry<Integer, Map<Integer, CrossNewMonopolyMarketGroup>> entry : CrossNewMonopolyMarketMgr.getMarketMap().entrySet()) {
                if(entry.getKey() != weekId){
                    continue;
                }
                for (Map.Entry<Integer, CrossNewMonopolyMarketGroup> groupEntry : entry.getValue().entrySet()) {
                    groupEntry.getValue().initOffice();
                    groupEntry.getValue().initNpcBlood();
                }
            }
        }catch (Exception e){
            CrossNewMonopolyMarketMgr.getLogger().info("error:", e);
        }


        try{
            //王帐、王宫的资源点数量、npc血量是根据活跃玩家的能力来生成，需要定时检测
            int weekId = GameConfig.getSystemThisWeekId();
            for (Map.Entry<Integer, Map<Integer, CrossNewMonopolyMarketGroup>> entry : CrossNewMonopolyMarketMgr.getMarketMap().entrySet()) {
                if(entry.getKey() != weekId){
                    continue;
                }
                for (Map.Entry<Integer, CrossNewMonopolyMarketGroup> groupEntry : entry.getValue().entrySet()) {
                    boolean init = false;
                    CrossNewMonopolyMarketGroup group = groupEntry.getValue();
                    for (Map.Entry<Integer, NewMonopolyMarketResGrab> resGrabEntry : group.getMarketResRob().getMarketResGrabMap().entrySet()) {
                        NewMonopolyMarketResGrab resGrab = resGrabEntry.getValue();
                        init = group.getMarketResRob().initMap(resGrab);
                    }
                    if(init){
                        //下发配置
                        NewMonopolyMarketProto.NewMonopolyMarketQueShuPointSync.Builder syncMsg = NewMonopolyMarketProto.NewMonopolyMarketQueShuPointSync.newBuilder();
                        for (Map.Entry<Integer, NewMonopolyMarketResGrab> resGrabEntry : group.getMarketResRob().getMarketResGrabMap().entrySet()) {
                            NewMonopolyMarketResGrab resGrab = resGrabEntry.getValue();
                            NewMonopolyMarketProto.NewMonopolyMarketResGrabPointTemp.Builder pointTemp = NewMonopolyMarketProto.NewMonopolyMarketResGrabPointTemp.newBuilder();
                            pointTemp.setResGroupId(resGrab.getResGroupId());
                            NewMonopolyMarketProto.NewMonopolyMarketResGrabMapEntity.Builder builder = NewMonopolyMarketProto.NewMonopolyMarketResGrabMapEntity.newBuilder();
                            builder.setSide(resGrab.map.side);
                            builder.setType(resGrab.map.type);
                            builder.addAllLevel(resGrab.map.indexLevelList);
                            builder.setRealNum(resGrab.map.realNum);
                            pointTemp.setRedGrabMap(builder);
                            syncMsg.addResMap(pointTemp);
                        }
                        for (Long sid :group.getWeekStateData().getServerIdList()) {
                            MessageHelper.sendPacket(sid, 0, YanQuMessageUtils.buildMessage(Protocol.S_NEW_MONOPOLY_MARKET_QUE_SHU_POINT_SYNC, syncMsg));
                        }
                    }
                }
            }
        }catch (Exception e){
            CrossNewMonopolyMarketMgr.getLogger().info("error:", e);
        }

        int now = DateHelper.getCurrentSecond();
        //结算资源点
        try{
            Set<Long> userSet = new HashSet<>();
            int weekId = GameConfig.getSystemThisWeekId();
            for (Map.Entry<Integer, Map<Integer, CrossNewMonopolyMarketGroup>> entry : CrossNewMonopolyMarketMgr.getMarketMap().entrySet()) {
                if(entry.getKey() != weekId){
                    continue;
                }
                for (Map.Entry<Integer, CrossNewMonopolyMarketGroup> groupEntry : entry.getValue().entrySet()) {
                    CrossNewMonopolyMarketGroup group = groupEntry.getValue();
                    synchronized (group.getMarketResRob()) {
                        for (Map.Entry<Integer, NewMonopolyMarketResGrab> resGrabEntry : group.getMarketResRob().getMarketResGrabMap().entrySet()) {
                            NewMonopolyMarketResGrab resGrab = resGrabEntry.getValue();

                            if (resGrab.minResGrabEndTime != 0 && resGrab.minResGrabEndTime <= now) {
                                resGrab.collectingPointInfoList.sort(Comparator.comparingInt(t -> t.baseInfo.getEndTime()));
                                while (resGrab.collectingPointInfoList.size() > 0){
                                    NewMonopolyMarketResGrabPointInfo pointInfo = resGrab.collectingPointInfoList.get(0);
                                    long userId = pointInfo.baseInfo.getUserId();
                                    boolean end = group.getMarketResRob().attemptSettlement(resGrab, pointInfo, now);
                                    if(end){
                                        userSet.add(userId);
                                        resGrab.minResGrabEndTime = 0;
                                    }else {
                                        group.getMarketResRob().setMinResGrabEndTime(resGrab, pointInfo);
                                        break;
                                    }
                                }
                            }
                        }
                    }

                    // 尝试刷新榷场
                    group.refreshMonopolyMarket(group.getWeekStateData().getOfficeRefreshTime(), now);
                }
            }

            // 通知这些玩家有奖励结算资源点
            for (long userId : userSet){
                UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(userId);
                if(userBaseInfo == null){
                    continue;
                }
                MessageHelper.sendPacket(userBaseInfo.getServerId(), userId , YanQuMessageUtils.buildMessage(Protocol.S_NEW_MONOPOLY_MARKET_NORMAL_SETTLEMENT_NOTIFY_FROM_CROSS));
            }

        }catch (Exception e){
            CrossNewMonopolyMarketMgr.getLogger().info("error:", e);
        }

        //锁定榜单（要在周日22点结算之后）
        try{
            for (Map.Entry<Integer, Map<Integer, CrossNewMonopolyMarketGroup>> entry : CrossNewMonopolyMarketMgr.getMarketMap().entrySet()) {
                for (Map.Entry<Integer, CrossNewMonopolyMarketGroup> groupEntry : entry.getValue().entrySet()) {
                    CrossNewMonopolyMarketGroup group = groupEntry.getValue();
                    group.lockRank(now);
                }
            }
        }catch (Exception e){
            CrossNewMonopolyMarketMgr.getLogger().info("error:", e);
        }

        //补发奖励
        try{
            int preWeekId = GameConfig.getSystemPreWeekId();
            for (Map.Entry<Integer, Map<Integer, CrossNewMonopolyMarketGroup>> entry : CrossNewMonopolyMarketMgr.getMarketMap().entrySet()) {
                if(entry.getKey() != preWeekId){
                    continue;
                }
                for (Map.Entry<Integer, CrossNewMonopolyMarketGroup> groupEntry : entry.getValue().entrySet()) {
                    CrossNewMonopolyMarketGroup group = groupEntry.getValue();
                    group.autoRewardTask();
                }
            }
        }catch (Exception e){
            CrossNewMonopolyMarketMgr.getLogger().info("error:", e);
        }

        //资源点未领取，发邮件
        try{
            for (Map.Entry<Integer, Map<Integer, CrossNewMonopolyMarketGroup>> entry : CrossNewMonopolyMarketMgr.getMarketMap().entrySet()) {
                for (Map.Entry<Integer, CrossNewMonopolyMarketGroup> groupEntry : entry.getValue().entrySet()) {
                    CrossNewMonopolyMarketGroup group = groupEntry.getValue();
                    group.getMarketResRob().sendResGrabReward(now);
                }
            }
        }catch (Exception e){
            CrossNewMonopolyMarketMgr.getLogger().info("error:", e);
        }

        //榷署待客茶结算
        try{
            for (Map.Entry<Integer, Map<Integer, CrossNewMonopolyMarketGroup>> entry : CrossNewMonopolyMarketMgr.getMarketMap().entrySet()) {
                for (Map.Entry<Integer, CrossNewMonopolyMarketGroup> groupEntry : entry.getValue().entrySet()) {
                    CrossNewMonopolyMarketGroup group = groupEntry.getValue();
                    group.getMarketOffice().sendTeaReward(now);
                }
            }
        }catch (Exception e){
            CrossNewMonopolyMarketMgr.getLogger().info("error:", e);
        }

        //资源占用率日志(周六10点30 至  周日21点30 每个小时)
        try{
            int thisWeekId = GameConfig.getSystemThisWeekId();
            for (Map.Entry<Integer, Map<Integer, CrossNewMonopolyMarketGroup>> entry : CrossNewMonopolyMarketMgr.getMarketMap().entrySet()) {
                if(entry.getKey() != thisWeekId){
                    continue;
                }
                for (Map.Entry<Integer, CrossNewMonopolyMarketGroup> groupEntry : entry.getValue().entrySet()) {
                    CrossNewMonopolyMarketGroup group = groupEntry.getValue();
                    group.statResUseInfo();
                }
            }
        }catch (Exception e){
            CrossNewMonopolyMarketMgr.getLogger().info("error:", e);
        }

        //公告
        try{
            int weekId = GameConfig.getSystemThisWeekId();
            for (Map.Entry<Integer, Map<Integer, CrossNewMonopolyMarketGroup>> entry : CrossNewMonopolyMarketMgr.getMarketMap().entrySet()) {
                if(entry.getKey() != weekId){
                    continue;
                }
                for (Map.Entry<Integer, CrossNewMonopolyMarketGroup> groupEntry : entry.getValue().entrySet()) {
                    CrossNewMonopolyMarketGroup marketGroup = groupEntry.getValue();
                    synchronized (marketGroup.getMarketResRob()){
                        for (Map.Entry<Integer, NewMonopolyMarketResGrab> resGrabEntry : marketGroup.getMarketResRob().getMarketResGrabMap().entrySet()) {
                            NewMonopolyMarketResGrab resGrab = resGrabEntry.getValue();
                            synchronized (resGrab.checkNoticeDataPointInfoSet){
                                Iterator<NewMonopolyMarketResGrabPointInfo> iterator = resGrab.checkNoticeDataPointInfoSet.iterator();
                                while (iterator.hasNext()){
                                    NewMonopolyMarketResGrabPointInfo pointInfo = iterator.next();
                                    if(pointInfo.noticeData == null){
                                        iterator.remove();
                                        continue;
                                    }
                                    if(DateHelper.getCurrentSecond() - pointInfo.noticeData.getTime() > GameConfig.NEWMONOPOLYMARKET_LEAVE_TIME){
                                        if(pointInfo.noticeData.getOccupyType() == 0){
                                            marketGroup.addNotice(pointInfo.noticeData);
                                            pointInfo.noticeData = null;
                                        }
                                        iterator.remove();
                                        continue;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            CrossNewMonopolyMarketMgr.getLogger().info("error:", e);
        }

    }

}
